'''
处理电压相关的值
'''

import re
from excutor.excutor import Excutor

class Voltage(Excutor):

    def __init__(self, data):
        super().__init__(data)
        ##取电压的key
        self.voltage = r'电压'
        self.pattrenNum = re.compile(r'[.]*[0-9]+[.]?[0-9]*')
        self.patternUnit = re.compile(r'Vac/Vdc|[kKmM]?[Vv][\s]?[AD]?C?[\s/]?[AD]?C?')

    
    #判断是否存在电压数据
    @staticmethod
    def Existence(data,voltage = r'电压'):
        return data[data['new_key'].str.contains(voltage)]['new_key'].count()
    

    #修改数据表
    def processingData(self):
        indexVoltage = self.data[self.data['new_key'].str.contains(self.voltage)].index
        for index in indexVoltage:
            newValueRef = self._get_new_value(index)
            self.data.loc[index,'new_value_ref'] = newValueRef
        return self.data


    #分析并处理old_value,返回new_value_ref
    def _get_new_value(self,index):
        oneRowData = self.data.loc[index]
        old_value = oneRowData['old_value']
        numbers = self.pattrenNum.findall(old_value)
        numbers = [self._compelet_decimal(x) for x in numbers]
        units = self.patternUnit.findall(old_value)
        if not (numbers or units):
            return old_value
        elif numbers and units:
            return self._circumatance1(oneRowData,numbers,units)
        elif numbers:
            return self._circumatance2(oneRowData,numbers)
        else:
            return old_value

    
    def _circumatance1(self,oneRowData,numbers,units):
        if len(numbers) == 1:
            return numbers[0] + units[0]
        if len(numbers) > 1:
            return numbers[0] + ' to ' + numbers[-1] + units[0]


    def _circumatance2(self,oneRowData,numbers):
        if len(numbers) == 1:
            return numbers[0] + 'V'
        if len(numbers) > 1:
            return numbers[0] + ' to ' + numbers[-1] + 'V'
    

    #将简写小数变为正常小数 例如.11
    def _compelet_decimal(self,num):
        if num[0] == '.':
            return '0' + num
        else:
            return num